import json
from fastapi import APIRouter, Security
from server.util import return_code, check_password, random_str, is_admin_user, en_password
from server.response import RespBody
from server.database import db_manager
from server.user_data import server_user_data
from .request.package_req import ReqPackage, DelectePackage

router = APIRouter(prefix='/package', tags=['包管理'])


@router.post('/', response_model=RespBody, summary='添加新的包',
             dependencies=[Security(is_admin_user, scopes=["allow"])])
async def add_new_package(post: ReqPackage):
    package_name = await db_manager.fetch_one("SELECT id FROM package WHERE name = :name AND status=1", {"name": post.name})
    if not package_name:
        add_data = post.model_dump()
        add_data["env_append"] = json.dumps(post.env_append)
        if add_data.get("id"):
            del add_data["id"]
        new_package_id = await db_manager.insert("package", add_data)
        return return_code(200)
    else:
        return return_code(401, msg="包已经存在")


@router.delete('/', response_model=RespBody, summary='删除包',
             dependencies=[Security(is_admin_user, scopes=["allow"])])
async def delete_package(post: DelectePackage):
    await db_manager.delete("package", "id = :id", {"id", post.id})


@router.update('/', response_model=RespBody, summary='更新包',
             dependencies=[Security(is_admin_user, scopes=["allow"])])
async def update_package(post: ReqPackage):
    package_name = await db_manager.fetch_one("SELECT id FROM package WHERE id = :id AND status=1", {"id": post.id})
    if not package_name:
        return return_code(401, msg="包不存在")
    update_data = post.model_dump()
    update_data["env_append"] = json.dumps(post.env_append)
    if update_data.get("id"):
        del update_data["id"]
    await db_manager.update("package", update_data, "id=:id", {"id": post.id})
